package top.littlejiang.onlinexam.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.littlejiang.onlinexam.common.base.BusinessException;
import top.littlejiang.onlinexam.common.base.Constant;
import top.littlejiang.onlinexam.common.utils.Result;
import top.littlejiang.onlinexam.service.OlexamFileService;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author chen
 * @Description
 * @since 2021/2/28 12:03
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @Resource
    private HttpServletResponse response;
    @Autowired
    private OlexamFileService fileService;

    /**
     * 获取图片
     * @param imageName
     * @throws IOException
     */
    @Validated
    @GetMapping(value = "/getImage/{imageName}")
    public void getImage(@PathVariable("imageName") String imageName) throws IOException {
        String suffix = imageName.substring(imageName.lastIndexOf(".") + 1);
        OutputStream os = null;
        try {
            BufferedImage image = fileService.getImage(imageName);
            response.setContentType("image/" + suffix);
            os = response.getOutputStream();

            if (image != null) {
                ImageIO.write(image, suffix, os);
            }
        } catch (IOException e) {
            throw new BusinessException("加载图片失败！");
        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
    }

    /**
     * 保存图片至本地
     * 通过yml 配置本地路径
     * @param file
     * @return
     */
    @PostMapping("/uploadimg")
    @ResponseBody
    @RequiresPermissions("olexam:home:home")
    public Result uploadImg(@RequestParam("image") MultipartFile file){
        String url = fileService.saveFile(file, Constant.PICTURE_URL);
        return Result.ok(url);
    }

}
